import React, {
  ReactElement,
  useContext,
  useEffect,
  useMemo,
  useState
} from 'react';
import { DeviceEventEmitter, Image, Text, View } from 'react-native';
import { RtcLocalView } from 'react-native-agora';

import styles from './style';
import { Store } from '../../../../reducer';
import {
  LiveUser,
  CoinProgressData,
  ShowFaceSuccessData,
  NoFaceData,
  SubmitSuccessData
} from '../../../../types';
import Corner from '../../../Graph/Corner';
import { phonePx } from '../../../../../../util/adapt';
import { CLASS_ROOM_RIGHT_SCALE, PPTType } from '../../../../constant';
import { classRoomGold, noFace } from '../../../../../../constant/resource';
import { getCoinProgress } from '../../../../store/coinProgress';
import { addCoinNumber, showFace } from '../../../../actions';
import {
  CLASS_ROOM_EVENT_SHOW_FACE_SUCCESS,
  CLASS_ROOM_EVENT_SUBMIT_SUCCESS,
  CLASS_ROOM_EVENT_UPDATE_COIN_PROGRESS,
  CLASS_ROOM_EVENT_UPDATE_NO_FACE
} from '../../../../event';
import GetCoinAnimate from '../../../GetCoinAnimate';
import { isIOS } from '../../../../../../constant';
import Log from '../../../../../../common/log';

let animatedEnd: any;

export default ({
  userId,
  userNickName,
  goldCoinNum,
  haveAnswer
}: LiveUser): ReactElement => {
  const [addGoldCoinNum, setAddGoldCoinNum] = useState<number>(0);
  const [addInstantGoldCoinNum, setAddInstantGoldCoinNum] = useState<number>(0);
  const [noFaceTime, setNoFaceTime] = useState<number>(-100);
  const [progress, setProgress] = useState(getCoinProgress());
  const [isStop, setIsStop] = useState(false);
  const [hideGoldCoin, setHideGoldCoin] = useState<boolean>(false);

  const showProgress = progress === 0 ? 0.05 : progress / 10;

  const { state } = useContext(Store);
  const {
    isJoinedChannel,
    channel,
    showProblemWait,
    showSignIn,
    currentPPT
  } = state;
  const { type } = currentPPT;
  const isProblem = type === PPTType.Problem;

  useEffect((): (() => void) => {
    const subscription = DeviceEventEmitter.addListener(
      CLASS_ROOM_EVENT_SHOW_FACE_SUCCESS,
      (data: ShowFaceSuccessData): void => {
        const { addGoldCoinNum: localAddGoldCoinNum } = data;
        setAddGoldCoinNum(localAddGoldCoinNum);
      }
    );
    return (): void => {
      if (subscription) {
        subscription.remove();
      }
    };
  }, [addGoldCoinNum, userId]);

  useEffect((): (() => void) => {
    const subscription = DeviceEventEmitter.addListener(
      CLASS_ROOM_EVENT_SUBMIT_SUCCESS,
      (data: SubmitSuccessData): void => {
        const {
          userId: localUserId,
          addGoldCoinNum: localAddGoldCoinNum
        } = data;
        if (Number(localUserId) === Number(userId)) {
          setAddInstantGoldCoinNum(localAddGoldCoinNum);
        }
      }
    );
    return (): void => {
      if (subscription) {
        subscription.remove();
      }
    };
  }, [userId]);

  useEffect((): (() => void) => {
    const subscription = DeviceEventEmitter.addListener(
      CLASS_ROOM_EVENT_UPDATE_NO_FACE,
      (data: NoFaceData): void => {
        const { time } = data;
        setNoFaceTime((currentTime): number => {
          if (time > 0 && time === 27 && currentTime > 0) {
            Log.i(
              'ClassRoom currentUser',
              JSON.stringify({ event: 'no face', time, currentTime })
            );
          } else if (time < 0 && currentTime < 28 && currentTime > 0) {
            Log.i(
              'ClassRoom currentUser',
              JSON.stringify({ event: 'have face', time, currentTime })
            );
          }
          return time;
        });
      }
    );
    return (): void => {
      if (subscription) {
        subscription.remove();
      }
    };
  }, []);

  useEffect((): (() => void) => {
    const subscription = DeviceEventEmitter.addListener(
      CLASS_ROOM_EVENT_UPDATE_COIN_PROGRESS,
      (data: CoinProgressData): void => {
        const {
          progress: progressData,
          canAddCoin,
          isStop: isStopData,
          animatedEnd: localAnimatedEnd
        } = data;
        animatedEnd = localAnimatedEnd;
        setProgress(progressData);
        setIsStop(isStopData);
        if (canAddCoin) {
          addCoinNumber();
          showFace();
        }
      }
    );
    return (): void => {
      if (subscription) {
        subscription.remove();
      }
    };
  }, []);

  return useMemo((): ReactElement => {
    return (
      <View style={styles.kid}>
        <View style={styles.live}>
          {isJoinedChannel &&
          channel &&
          !showSignIn &&
          !showProblemWait &&
          isIOS ? (
            <RtcLocalView.SurfaceView
              style={styles.video}
              renderMode={1}
              channelId={channel}
              zOrderMediaOverlay
              // zOrderOnTop
              key={`${channel}-${userId}`}
            />
          ) : null}
          {isJoinedChannel &&
          channel &&
          !showSignIn &&
          !showProblemWait &&
          !isIOS ? (
            <RtcLocalView.TextureView
              style={styles.video}
              renderMode={1}
              channelId={channel}
              key={`${channel}-${userId}`}
            />
          ) : null}
          {isProblem && !haveAnswer && (
            <View style={styles.problem}>
              <Text style={styles.problemDesc}>正在做题</Text>
            </View>
          )}
          {addInstantGoldCoinNum > 0 ? (
            <GetCoinAnimate
              addGoldCoinNum={addInstantGoldCoinNum}
              clearGoldCoinNum={(): void => {
                setAddInstantGoldCoinNum(0);
                setHideGoldCoin(false);
              }}
              style={styles.instantCoin}
              x={phonePx(46.2) * CLASS_ROOM_RIGHT_SCALE}
              y={phonePx(-9.8) * CLASS_ROOM_RIGHT_SCALE}
              scale={0.55556}
              showAddNumber={false}
              hideGoldCoinNum={(): void => {
                setHideGoldCoin(true);
              }}
            />
          ) : (
            <View />
          )}
          {noFaceTime > -1 && (
            <View style={styles.noFaceContent}>
              <Image source={noFace} style={styles.noFace} />
              <Text style={styles.noFaceDesc}>{noFaceTime}秒后自动锁定</Text>
            </View>
          )}
          <Corner
            style={styles.corner}
            width={phonePx(66) * CLASS_ROOM_RIGHT_SCALE}
            height={phonePx(66) * CLASS_ROOM_RIGHT_SCALE}
            dia={phonePx(2) * CLASS_ROOM_RIGHT_SCALE}
            fillColor="#ffffff"
          />
        </View>
        <View style={styles.info}>
          <Text style={styles.name} numberOfLines={1}>
            {userNickName}
          </Text>
          <View style={styles.coinContent}>
            {hideGoldCoin ? (
              <View style={styles.coin} />
            ) : (
              <Image source={classRoomGold} style={styles.coin} />
            )}
            <Text style={styles.number}>{goldCoinNum}</Text>
          </View>
          <View style={styles.coinProgress}>
            <Text style={styles.desc}>金币进度</Text>
            <Text style={styles.progressDesc}>{progress}/10</Text>
          </View>
          <View style={styles.progress}>
            <View style={styles.content} />
            <View
              style={[
                styles.progressContent,
                {
                  left:
                    phonePx(70) * CLASS_ROOM_RIGHT_SCALE * (showProgress - 1)
                },
                isStop ? styles.gray : {}
              ]}
            />
          </View>
        </View>
        {addGoldCoinNum > 0 ? (
          <GetCoinAnimate
            addGoldCoinNum={addGoldCoinNum}
            clearGoldCoinNum={(): void => {
              if (animatedEnd) {
                animatedEnd();
                animatedEnd = null;
              }
              setAddGoldCoinNum(0);
              setHideGoldCoin(false);
            }}
            style={styles.getCoin}
            x={phonePx(-65.2) * CLASS_ROOM_RIGHT_SCALE}
            y={phonePx(-35.8) * CLASS_ROOM_RIGHT_SCALE}
            scale={1}
            showAddNumber={false}
            width={phonePx(10) * CLASS_ROOM_RIGHT_SCALE}
            height={phonePx(10) * CLASS_ROOM_RIGHT_SCALE}
            needSound={false}
            hideGoldCoinNum={(): void => {
              setHideGoldCoin(true);
            }}
          />
        ) : (
          <View />
        )}
      </View>
    );
  }, [
    addGoldCoinNum,
    addInstantGoldCoinNum,
    channel,
    goldCoinNum,
    haveAnswer,
    hideGoldCoin,
    isJoinedChannel,
    isProblem,
    isStop,
    noFaceTime,
    progress,
    showProblemWait,
    showProgress,
    showSignIn,
    userId,
    userNickName
  ]);
};
